package com.zmn.oms.zmn.business.impl.account;

import com.alibaba.fastjson.JSON;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.model.dto.account.OrderAutoAccountResultDTO;
import com.zmn.oms.model.entity.account.OrderAccountResult;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.account.OrderAccountResultService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.zmn.business.interfaces.account.OrderAutoAccountResultBService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 描述：
 *
 * @author xiewenbing
 * @since 2022/8/17 16:37
 */
@Slf4j
@Service
public class OrderAutoAccountResultBServiceImpl implements OrderAutoAccountResultBService {

    @Autowired
    private OrderWorkService orderWorkService;

    @Autowired
    private OrderAccountResultService orderAccountResultService;

    /**
     * 保存算账结果
     * @param orderAutoAccountResultDTO
     */
    @Override
    public void saveOrderAutoAccountResult(OrderAutoAccountResultDTO orderAutoAccountResultDTO) throws OmsBaseException {

        if (Objects.isNull(orderAutoAccountResultDTO)) {
            throw new OmsBaseException("参数不能为Null");
        }

        OrderAccountResult orderAccountResult = BeanMapper.map(orderAutoAccountResultDTO, OrderAccountResult.class);
        String checksum = DigestUtils.md5Hex(JSON.toJSONString(orderAccountResult));
        if (StringUtil.isBlank(checksum) || checksum.compareToIgnoreCase(orderAutoAccountResultDTO.getChecksum()) != 0) {
            throw new OmsBaseException("校验失败");
        }

        // 查找工单
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderAutoAccountResultDTO.getOrderId(),
                orderAutoAccountResultDTO.getWorkId());
        if (Objects.isNull(orderWork)) {
            throw new OmsBaseException("查找不到对应的工单");
        }

        // 收单状态判断
        if (!Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_CHECKOUT)) {
            throw new OmsBaseException("工单状态不为收单");
        }

        // 保存到数据表
        orderAccountResultService.insert(orderAccountResult);
    }
}
